package com.wanglibao.woodtrade.woodtrade.ui.activity;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.Drawable;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Html;
import android.util.DisplayMetrics;
import android.view.View;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.TextView;

import com.google.gson.Gson;
import com.squareup.picasso.Picasso;
import com.wanglibao.woodtrade.woodtrade.R;
import com.wanglibao.woodtrade.woodtrade.config.NetConfig;
import com.wanglibao.woodtrade.woodtrade.entity.InformationDetails;
import com.wanglibao.woodtrade.woodtrade.jsonrpc.JsonRPCAsyncTask;

import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;

import butterknife.Bind;
import butterknife.ButterKnife;
/*资讯详情内页，呈现一些信息*/
public class InformationDetailActivity extends BaseActivity {


    @Bind(R.id.sdv_information_detail_activity)
    ImageView mSdvInformationDetailActivity;
//    @Bind(R.id.ll_information_detail_activity)
//    LinearLayout mLlInformationDetailActivity;
    @Bind(R.id.tv_title_information_wood_activtiy)
    TextView mTvTitleInformationWoodActivtiy;
    @Bind(R.id.tv_contact_information_detail_activity)
    TextView mTvContactInformationDetailActivity;
    @Bind(R.id.tv_from_information_detail_activity)
    TextView mTvFromInformationDetailActivity;
    @Bind(R.id.tv_autor_information_detail_activity)
    TextView mTvAutorInformationDetailActivity;
    @Bind(R.id.tv_data_information_detail_activity)
    TextView mTvDataInformationDetailActivity;
    //=======================================
    InformationDetails mDetails=null;
    String requestID=null;
    Gson mGson=new Gson();
    Handler mHandler=new Handler(new Handler.Callback() {
        @Override
        public boolean handleMessage(Message msg) {
            if(msg.arg2!=2){
                if(msg.arg1==NetConfig.TaskId.newDetail){
                    mDetails=mGson.fromJson(msg.obj.toString(),InformationDetails.class);
                    appearData();
                }
            }
//            if (msg.arg2==20){
//                mSdvInformationDetailActivity.setImageBitmap((Bitmap) msg.obj);
//            }
            return false;
        }
    });
    int width;
    int height;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_information_detail);
        ButterKnife.bind(this);
        if (Build.VERSION.SDK_INT >= 19) {
            getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
        } else {
            rl_common_title.setPadding(0, 0, 0, 0);
        }
        initData();
        DisplayMetrics metric = new DisplayMetrics();
        getWindowManager().getDefaultDisplay().getMetrics(metric);
        width = metric.widthPixels;     // 屏幕宽度（像素）
        height = metric.heightPixels;   // 屏幕高度（像素）
        float density = metric.density;      // 屏幕密度（0.75 / 1.0 / 1.5）
        int densityDpi = metric.densityDpi;  // 屏幕密度DPI（120 / 160 / 240）
    }

    private void initData() {
        tvTitle.setText("资讯详情");
        tvBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        requestID=getIntent().getStringExtra("Id");
        netWorking(requestID);
        
    }
    /*连接网络，获取数据*/
    public void netWorking(String requestID){
        if (requestID!=null){
            JsonRPCAsyncTask jsonRPCAsyncTask = new JsonRPCAsyncTask(this, NetConfig.SERVER + NetConfig.TYPE_NEW,
                    NetConfig.newDetail, mHandler, "jsonObject", NetConfig.TaskId.newDetail, new Object[]{requestID});
            jsonRPCAsyncTask.execute(new Void[]{});
        }else {
        }
    }
    /*将拿回的数据 呈现在控件上面*/
    public void appearData(){
        String html="<html><head><title>TextView使用HTML</title></head><body><p><strong>强调</strong></p><p><em>斜体</em></p>"
                +"<p><a href=\"http://www.dreamdu.com/xhtml/\">超链接HTML入门</a>学习HTML!</p><p><font color=\"#aabb00\">颜色1"
                +"</p><p><font color=\"#00bbaa\">颜色2</p><h1>标题1</h1><h3>标题2</h3><h6>标题3</h6><p>大于>小于<</p><p>" +
                "下面是网络图片</p><img src=\"http://avatar.csdn.net/0/3/8/2_zhang957411207.jpg\"/></body></html>";
//        System.out.println("mDetails.getImgUrl():"+mDetails.getImgUrl());
        Picasso.with(this).load(mDetails.getImgUrl()).into(mSdvInformationDetailActivity);
        mTvTitleInformationWoodActivtiy.setText(mDetails.getTitle());
        mTvContactInformationDetailActivity.setText(Html.fromHtml(mDetails.getContent()));
        mTvFromInformationDetailActivity.setText("来源："+mDetails.getSource());
        mTvAutorInformationDetailActivity.setText("作者："+mDetails.getAuthor());
        mTvDataInformationDetailActivity.setText("时间："+mDetails.getCreate_time().substring(0,10));
//        getBitmap(mDetails.getImgUrl());
//        new Thread(new Runnable() {
//            @Override
//            public void run() {
//                Bitmap drawable=getBitmap(mDetails.getImgUrl());
//                Width=drawable.getWidth();
//                Height=drawable.getHeight();
//                System.out.println("width"+drawable.getWidth());
//                System.out.println("height"+drawable.getHeight());
//                Message message=mHandler.obtainMessage();
//                message.obj=drawable;
//                message.arg2=20;
//                mHandler.sendMessage(message);
//            }
//        }).start();
    }
//    int Width;
//    int Height;
    //连接网络，获取网络上的图片
    public Bitmap getBitmap(String url){
        Bitmap bitmap =null;
        HttpURLConnection conn = null;
        try {
            //建立网络连接
            conn = (HttpURLConnection) new URL(url).openConnection();
            conn.setRequestMethod("GET");//GET方式
            conn.setConnectTimeout(10000);
            conn.setReadTimeout(10000);
            //返回码


                //获得网络上返回的流
                InputStream is = conn.getInputStream();
                //将流转为图片
                bitmap = BitmapFactory.decodeStream(is);
                System.out.println("bitmap.width"+bitmap.getWidth());
                System.out.println("bitmap.height"+bitmap.getHeight());
                mSdvInformationDetailActivity.setImageBitmap(bitmap);

        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }finally{
            if(conn!=null){
                conn.disconnect();//关闭连接
            }
        }
        return bitmap;
    }
    /**
     * @param urlpath
     * @return Bitmap
     * 根据url获取布局背景的对象
     */
    public static Drawable getDrawable(String urlpath){
        Drawable d = null;
        try {
            URL url = new URL(urlpath);
            URLConnection conn = url.openConnection();
            conn.connect();
            InputStream in;
            in = conn.getInputStream();
            d = Drawable.createFromStream(in, "background.jpg");
            // TODO Auto-generated catch block
        } catch (IOException e) {
            e.printStackTrace();
        }
        return d;
    }
}
